package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ManipulateGridSquad extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ManipulateGridSquad() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = wid.getConn(true);
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		String strSQL = "";
		String oper = request.getParameter("oper");						//增刪改查那一種
		final String bssId = "MBMS";
		String squadId = request.getParameter("squadId");
		String subSysId = request.getParameter("subSysId");
		String squadpath = request.getParameter("squadPath");						//部署班的部署路徑
		String result = "";
		final String currentUser = request.getParameter("currentUser");
		
		try {
			/** 判別需進行何種操作 **/
			if ( "del".equalsIgnoreCase(oper) ) {
				/*	刪除資訊群組下所包含的 主機	*/
				strSQL = "DELETE FROM mpsquadhosts WHERE bssid=? AND subsysid=? AND squadid=?";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, bssId);
				ps.setString(2, subSysId);
				ps.setString(3, squadId);
				ps.execute();
				
				/*	刪除環境下所包含的資訊群組	*/
				strSQL = "DELETE FROM mpsquadenv WHERE bssid=? AND subsysid=? AND squadid=?";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, bssId);
				ps.setString(2, subSysId);
				ps.setString(3, squadId);
				ps.execute();
				
				/*	刪除資訊群組	*/
				strSQL = "DELETE FROM squad WHERE bssid=? AND subsysid=? AND squadid=?";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, bssId);
				ps.setString(2, subSysId);
				ps.setString(3, squadId);
				ps.execute();
				
				wid.keepLogProfile(wid.SQUAD, wid.DELETE, currentUser, conn, ps);
				result = "刪除了"+squadId;
			} else if ( "add".equalsIgnoreCase(oper) ) {
				if (!isDuplicated(squadId,bssId,subSysId,conn,ps,rs)) {
					strSQL = "INSERT INTO squad (subsysid,squadname,creator,createdDateTime,bssid,squadid,squadpath) VALUES (?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, subSysId);
					ps.setString(2, wid.UI2DB( request.getParameter("squadName"),conn.getMetaData().getDatabaseProductName() ) );
					ps.setString(3, currentUser);
					ps.setTimestamp(4, wid.currentTimeStamp());
					ps.setString(5, bssId);
					ps.setString(6, squadId);
					ps.setString(7, squadpath);
					ps.execute();
					
					wid.keepLogProfile(wid.SQUAD, wid.ADD, currentUser, conn, ps);
					result = "新增完成 "+squadId;
				} else {
					result = squadId+" 已存在 !";		
				}
			} else if ( "edit".equalsIgnoreCase(oper) ) {
				strSQL = "UPDATE squad SET squadid=?,squadname=?,squadpath=?,lastUpdator=?,lastUpdatedDateTime=? WHERE subsysid=? AND bssid=? AND squadid=?";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, squadId);
				ps.setString(2, wid.UI2DB( request.getParameter("squadName"),conn.getMetaData().getDatabaseProductName() ) );
				ps.setString(3, squadpath);
				ps.setString(4, currentUser);
				ps.setTimestamp(5, wid.currentTimeStamp());
				ps.setString(6, subSysId);
				ps.setString(7, bssId);
				ps.setString(8, squadId);
				ps.execute();
				
				wid.keepLogProfile(wid.SQUAD, wid.UPDATE, currentUser, conn, ps);
				result = "修改完成 "+squadId;
			}
		} catch ( UnsupportedEncodingException e ) {
			result = "異動"+squadId+"失敗!!\n\n";
			result += wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch ( SQLException e) {
			result = "異動"+squadId+"失敗!!\n\n";
			result += wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch ( Exception e) {
			result = "異動"+squadId+"失敗!!\n\n";
			result += wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if (rs!= null) { rs.close(); }
				if (ps!= null) { ps.close(); }
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}	
		}
		
		response.getWriter().write(result);		
	}
	
	private boolean isDuplicated(String squadId,String bssId,String subSysId,Connection conn,PreparedStatement ps, ResultSet rs) throws SQLException {
		String strSQL = "SELECT COUNT(*) FROM squad WHERE squadid=? AND bssid=? AND subsysid=? ";
		
		ps = conn.prepareStatement(strSQL);
		ps.setString(1, squadId);
		ps.setString(2, bssId);
		ps.setString(3, subSysId);
		rs = ps.executeQuery();
		rs.next();

		return rs.getInt(1) == 0?false:true;
	}
}